package com.wstuo.common.config.customfilter.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.wstuo.common.config.category.dao.ICICategoryDAO;
import com.wstuo.common.config.category.entity.CICategory;
import com.wstuo.common.config.category.entity.Category;
import com.wstuo.common.config.customfilter.dto.EasyExpression;
import com.wstuo.common.config.customfilter.dto.KeyTransferDTO;
import com.wstuo.common.config.customfilter.entity.CustomExpression;
import com.wstuo.common.config.customfilter.entity.CustomFilter;
import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.service.IOrganizationService;
import com.wstuo.common.util.DaoUtils;
import com.wstuo.common.util.TimeUtils;


public class FilterDAO extends BaseDAOImplHibernate<CustomFilter> implements IFilterDAO{
	/**
     * 获取用户的过滤器
     * @param qdto
     * @return RequestCountResultDTO
     * 
     */
	@Autowired
	private IUserDAO userDAO;
	@Autowired
    private IOrganizationService organizationService;
	@Autowired
	private ICICategoryDAO cicategoryDAO;
	/**
	 * 
	 * @param orgNo
	 * @return Long []
	 */
	public Long [] findByShareOrgNo(Long orgNo){
		DetachedCriteria dc = DetachedCriteria.forClass(CustomFilter.class);
		dc.createAlias("shareGroups", "gps");
		Long[] orgNos = organizationService.reverFindOrg(new Long[]{orgNo});
    	dc.add(Restrictions.in("gps.orgNo", orgNos));
    	@SuppressWarnings("unchecked")
		List<CustomFilter> filters=super.getHibernateTemplate().findByCriteria(dc);
    	Long [] ids=new Long[filters.size()];
    	int i=0;
    	for(CustomFilter cf:filters){
    		ids[i]=cf.getFilterId();
    		i++;
    	}
    	return ids;
	}
	/**
	 * 查询分享到组的.
	 * @param filterCategory
	 * @param userName
	 * @return List<CustomFilter>
	 */
	@SuppressWarnings("unchecked")
	public List<CustomFilter> findGroupShare(String filterCategory,String userName){
		DetachedCriteria dc = DetachedCriteria.forClass(CustomFilter.class);
		if(null != filterCategory){
			dc.add(Restrictions.eq("filterCategory", filterCategory));
		}
		
		dc.createAlias("shareGroups", "gps");
		
		Set<Organization> orgNos = new HashSet<Organization>();
    	
		User user = userDAO.findUniqueBy("loginName", userName);
		if(user!=null){
			orgNos=userDAO.findUniqueBy("loginName", userName).getBelongsGroup();
		}
    	Long[] gpOrgNos ;
    	if(orgNos!=null && orgNos.size()>0){
    		int i = 0;
    		gpOrgNos = new Long[orgNos.size()];
    		for (Organization org : orgNos) {
    			gpOrgNos[i] = org.getOrgNo();
    			i++;
			}
    	}else{
    		gpOrgNos = new Long[]{0L};
    	}
    	dc.add(Restrictions.eq("share", "sharegroup"));
    	dc.add(Restrictions.in("gps.orgNo",gpOrgNos));
    	return super.getHibernateTemplate().findByCriteria(dc);
	}

	@SuppressWarnings("unchecked")
	public List<CustomFilter> findFiltersByUser(String userName,//Long userOrgNo,
			String filterCategory){
    	DetachedCriteria dc = DetachedCriteria.forClass(CustomFilter.class);
    	if(null != filterCategory){
    		dc.add(Restrictions.eq("filterCategory", filterCategory));
    	}
    	//第一段MyShare
    	SimpleExpression l=Restrictions.eq("creator", userName);
    	SimpleExpression r=Restrictions.eq("share", "share");
    	LogicalExpression myShare=Restrictions.or(r, l);
    	dc.add(myShare);
    
    	List<CustomFilter> group=findGroupShare(filterCategory,userName);
    	List<CustomFilter> my_share = super.getHibernateTemplate().findByCriteria(dc);
    	my_share.addAll(group);
    	
    	return my_share;
    }
    
	/**
     * 获取我的过滤器。
     * @param userName
     * @param filterCategory
     * @return  List<CustomFilter>
     * 
     */
    @SuppressWarnings("unchecked")
	public List<CustomFilter> findMyFilters(String userName,String filterCategory){
    	String hql="from CustomFilter f where f.dataFlag not in(99) and f.filterCategory=? and f.creator=?";
    	return super.getHibernateTemplate().find(hql,filterCategory,userName);
    }
    
    /**
     * 根据过滤器查询数据，并取得关联关系列表.(报表)
     * @param filter
     * @param dc
     * @return List<String>
     */
    public List<String> setFilterDetachedCriteria(CustomFilter filter,Map<Long,String> selfExpressions,DetachedCriteria dc){
       List<String> aliasList=new ArrayList<String>();
       List<String> aliaList=new ArrayList<String>();
       if(filter!=null){
	  	   Disjunction dj = Restrictions.disjunction();
	  	   Conjunction cj = Restrictions.conjunction();
	  	   dc.add(cj);
	  	   cj.add(dj);
	  	   List<CustomExpression> exps = filter.getExpressions();
	  	   //将过滤器的参数值替换我自定义的。
	  	   if(selfExpressions!=null && selfExpressions.keySet().size()>0){
	  		   for(Long key:selfExpressions.keySet()){
	  			   for(CustomExpression c:exps){
	  				   if(c.getExpId().equals(key)){
	  					   c.setPropValue(selfExpressions.get(key));
	  				   }
	  			   }
	  		   }
	  	   }
	  	   Long cno=0l;
	  	   if(exps!=null&&exps.size()>0){
				for (CustomExpression exp:  exps){
					if(exp.getPropName().equals("category.cno")){
						cno=Long.parseLong(exp.getPropValue());
					}
				}
			}
	  	   if (cno!=0l && "com.wstuo.itsm.cim.entity.CI".equals(filter.getEntityClass())) {
				CICategory entity = cicategoryDAO.findConfigureItemTreeByParentEventId(cno);
				List<Long> cnolist=new ArrayList<Long>();
				cicategoryDAO.findChildrenCno(entity, cnolist);
				cnolist.add(cno);
				dc.createAlias("category", "category",CriteriaSpecification.LEFT_JOIN);
				Long[] cicno=cnolist.toArray(new Long[cnolist.size()]);
				dc.add(Restrictions.in("category.cno",cicno));
				aliaList.add("category");
			}
	  	   @SuppressWarnings("rawtypes")
	  	   Set set=new HashSet();
	  	   if(exps!=null&&exps.size()>0){
	  		   	//上一个的连接类型
				String joinType = "";
				for (CustomExpression exp:  exps) {
					if(exp.getPropName().indexOf("eav_")>-1){
						String attrType="string";
						if(exp.getPropType().equals("Long")) 
							attrType="datadictionary";
						List list= findByAttrValue(attrType,exp.getPropValue(),exp.getOperator(),filter.getEntityClass(),exp.getPropName());
						if(list!=null&list.size()>0){
							if("and".equals(joinType)){
								dj = Restrictions.disjunction();
								cj.add(dj);
							}
							Long[] id=new Long[list.size()];
							for (int j = 0; j < list.size(); j++) {
								id[j]=Long.valueOf(list.get(j).toString());
							}
							if("com.wstuo.itsm.cim.entity.CI".equals(filter.getEntityClass())){
								dj.add(Restrictions.in("ciId", id));
							}else if("com.wstuo.itsm.request.entity.Request".equals(filter.getEntityClass()))
								dj.add(Restrictions.in("eno", id));
						}
					}else if( "com.wstuo.itsm.cim.entity.CI".equals(filter.getEntityClass()) && !exp.getPropName().equals("category.cno")){
						if("and".equals(joinType)){
							dj = Restrictions.disjunction();
							cj.add(dj);
						}
						dj.add(createEasyExpression(exp, dc,set,aliaList));
					}else if(exp.getOperator().contains("in")){
						String[] propValue=exp.getPropValue().split(",");
						Long[] num = new Long[propValue.length];
						for (int idx = 0; idx < propValue.length; idx++) {
				            num[idx] = Long.parseLong(propValue[idx]);
				        }
						if(exp.getOperator().equals("in")){
							if("and".equals(joinType)){
								cj.add(Restrictions.in(exp.getPropName(), num));
								dc.add(cj);
							}else{
								dj.add(Restrictions.in(exp.getPropName(), num));
								dc.add(dj);
							}
						}else{
							if("and".equals(joinType)){
								cj.add(Restrictions.not(Restrictions.in(exp.getPropName(),num)));
								dc.add(cj);
							}else{
								dj.add(Restrictions.not(Restrictions.in(exp.getPropName(),num)));
								dc.add(dj);
							}
						}
					}else{
						if(exp.getPropName()!=null && exp.getPropName().indexOf(".")!=-1){
							aliasList.add(exp.getPropName().substring(0,exp.getPropName().indexOf(".")));
						}
						//如果上一个连接类型是and
						if("and".equals(joinType)){
							dj = Restrictions.disjunction();
							cj.add(dj);
						}
						dj.add(createEasyExpression(exp, dc,set,aliaList));
					}
					joinType = exp.getJoinType();
				}
	  	   }
       }
       return aliasList;
    }

    
    /**
     * 通过过滤器查询实体数据
     * @param filter
     * @return PageDTO
     * 
     */
    public PageDTO findPageByCustomFilter(CustomFilter filter, int start , int limit,String sidx,String sord) {
    	return findPageByCustomFilter(filter, null,null ,start ,limit,sidx,sord);
    }
    
    

	/**
     * 通过过滤器查询实体数据
     * @param filter
     * @return PageDTO
     *  
     */
    @SuppressWarnings("deprecation")
	public PageDTO findPageByCustomFilter(CustomFilter filter,Long [] companyNos,Long[] categorys, int start , int limit,String sidx,String sord) {
    	List<String> aliaList=new ArrayList<String>();
    	DetachedCriteria dc = DetachedCriteria.forEntityName(filter.getEntityClass());  
    	Disjunction dj = Restrictions.disjunction();
		Conjunction cj = Restrictions.conjunction();
		List<CustomExpression> exps = filter.getExpressions();
		dc.add(cj);
		cj.add(dj);
		//只查找我负责的公司 问题
		if(companyNos!=null && companyNos.length>0){
			dc.add(Restrictions.in("companyNo", companyNos));
		}
		
		boolean result=true;
		Long cno=0l;
		if(exps!=null&&exps.size()>0){
			for (CustomExpression exp:  exps){
				if(exp.getPropName().equals("requestCategory.eventId")){
					result=false;
				}
				else if(exp.getPropName().equals("category.cno")){
					cno=Long.parseLong(exp.getPropValue());
				}
			}
		}
		
		//分类权限过滤 category.cno
		if (result && categorys != null && categorys.length > 0 && "com.wstuo.itsm.request.entity.Request".equals(filter.getEntityClass())) {
				dc.createAlias("requestCategory", "rc",CriteriaSpecification.LEFT_JOIN);
				dc.add(Restrictions.or(
						Restrictions.in("rc.eventId",categorys),
						Restrictions.isNull("rc.eventId")));
		}
		if (cno!=0l && "com.wstuo.itsm.cim.entity.CI".equals(filter.getEntityClass())) {
			CICategory entity = cicategoryDAO.findConfigureItemTreeByParentEventId(cno);
			List<Long> cnolist=new ArrayList<Long>();
			cicategoryDAO.findChildrenCno(entity, cnolist);
			cnolist.add(cno);
			dc.createAlias("category", "category",CriteriaSpecification.LEFT_JOIN);
			Long[] cicno=cnolist.toArray(new Long[cnolist.size()]);
			dc.add(Restrictions.in("category.cno",cicno));
			aliaList.add("category");
		}
		//排序
		dc = DaoUtils.orderBy(sidx, sord, dc);
		@SuppressWarnings("rawtypes")
		Set set=new HashSet();
		
		if(exps!=null&&exps.size()>0){
			//上一个的连接类型
			String joinType = "";
			for (CustomExpression exp:  exps) {
				//如果上一个连接类型是and
				if(exp.getPropName().indexOf("eav_")>-1){
					String attrType="string";
					if(exp.getPropType().equals("Long")) 
						attrType="datadictionary";
					List list= findByAttrValue(attrType,exp.getPropValue(),exp.getOperator(),filter.getEntityClass(),exp.getPropName());
					if(list!=null&list.size()>0){
						if("and".equals(joinType)){
							dj = Restrictions.disjunction();
							cj.add(dj);
						}
						Long[] id=new Long[list.size()];
						for (int j = 0; j < list.size(); j++) {
							id[j]=Long.valueOf(list.get(j).toString());
						}
						if("com.wstuo.itsm.cim.entity.CI".equals(filter.getEntityClass())){
							dj.add(Restrictions.in("ciId", id));
						}else if("com.wstuo.itsm.request.entity.Request".equals(filter.getEntityClass()))
							dj.add(Restrictions.in("eno", id));
					}
				}else if( "com.wstuo.itsm.cim.entity.CI".equals(filter.getEntityClass()) && !exp.getPropName().equals("category.cno")){
					if("and".equals(joinType)){
						dj = Restrictions.disjunction();
						cj.add(dj);
					}
					dj.add(createEasyExpression(exp, dc,set,aliaList));
				}else if(exp.getOperator().contains("in")){
					String[] propValue=exp.getPropValue().split(",");
					Long[] num = new Long[propValue.length];
					for (int idx = 0; idx < propValue.length; idx++) {
			            num[idx] = Long.parseLong(propValue[idx]);
			        }
					if(exp.getOperator().equals("in")){
						if("and".equals(joinType)){
							cj.add(Restrictions.in(exp.getPropName(), num));
							dc.add(cj);
						}else{
							dj.add(Restrictions.in(exp.getPropName(), num));
							dc.add(dj);
						}
					}else{
						if("and".equals(joinType)){
							cj.add(Restrictions.not(Restrictions.in(exp.getPropName(),num)));
							dc.add(cj);
						}else{
							dj.add(Restrictions.not(Restrictions.in(exp.getPropName(),num)));
							dc.add(dj);
						}
					}
				}else{
					if("and".equals(joinType)){
						dj = Restrictions.disjunction();
						cj.add(dj);
					}
					dj.add(createEasyExpression(exp, dc,set,aliaList));
				}
				joinType = exp.getJoinType();
			}
		}
		
		PageDTO dto = new PageDTO();
		dto = super.findPageByCriteria(dc, start, limit);
		return dto;
    }
	private List  findByAttrValue(final String attrType,final String attrValue,final String operator,final String entityClass,final String propName){
		 return getHibernateTemplate().executeFind(new HibernateCallback(){  
		        public Object doInHibernate(Session session)  throws HibernateException, SQLException {  
		        	//string datadictionary
		        	String sql="SELECT ev.eno FROM eventeav ev,eventeav_attributevalue val,attributevalue"+attrType+" av "+
		        			"WHERE ev.eventeavid=val.eventeav_eventeavid AND val.attrvals_attrvalsno=av.attrvalsno AND ev.eventType='itsm.request' "+
		        			"AND av.attrvalue "+operator+" ?";
		        	if("com.wstuo.itsm.cim.entity.CI".equals(entityClass)){
		        		sql="SELECT cv.CI_ciId FROM attribute a,attributevalue b,attributevaluestring av,ci_attributevalue cv " +
			        			"WHERE a.attrNo=b.attrNo AND av.attrValsNo=b.attrValsNo AND cv.attrVals_attrValsNo= b.attrValsNo " +
			        			"AND a.attrName='"+propName+"' AND av.attrValue "+operator+" ?";
		        	}
		            Query q = session.createSQLQuery(sql);  
		            q.setParameter(0, attrValue);
		            return q.list();  
		        }             
		    });  
	}

    /**
     * 通过过滤器查询实体数据
     * @param filter
     * @return List
     * 
     */
    @SuppressWarnings("rawtypes")
    public List findByCustomFilter(CustomFilter filter,Long [] companyNos,Long[] categorys, int start , int limit,String sidx,String sord) {
    	List<String> aliaList=new ArrayList<String>();
    	DetachedCriteria dc = DetachedCriteria.forEntityName(filter.getEntityClass());   
    	Disjunction dj = Restrictions.disjunction();
		Conjunction cj = Restrictions.conjunction();
		List<CustomExpression> exps = filter.getExpressions();
		dc.add(cj);
		cj.add(dj);
		//只查找我负责的公司 问题
		if(companyNos!=null && companyNos.length>0){
			dc.add(Restrictions.in("companyNo", companyNos));
		}
		boolean result=true;
		if(exps!=null){
			for (CustomExpression exp:  exps){
				if(exp.getPropName().equals("requestCategory.eventId")){
					result=false;
				}
			}
		}
		//分类权限过滤
		if (result && categorys != null && categorys.length > 0 && "com.wstuo.itsm.request.entity.Request".equals(filter.getEntityClass())) {
				dc.createAlias("requestCategory", "rc",CriteriaSpecification.LEFT_JOIN);
				dc.add(Restrictions.or(
						Restrictions.in("rc.eventId",categorys),
						Restrictions.isNull("rc.eventId")));
		} 
		//排序
		dc = DaoUtils.orderBy(sidx, sord, dc);
		Set set=new HashSet();
		
		if(exps!=null&&exps.size()>0){
			//上一个的连接类型
			String joinType = "";
			for (CustomExpression exp:  exps) {
				//如果上一个连接类型是and
				if("and".equals(joinType)){
					dj = Restrictions.disjunction();
					cj.add(dj);
				}
				dj.add(createEasyExpression(exp, dc,set,aliaList));
				
				joinType = exp.getJoinType();
			}
		}
		List list = super.getHibernateTemplate().findByCriteria(dc, start, limit);
		return list;
    }
    
    /**
     * 根据过滤器条件创建表达式
     */
	@SuppressWarnings("unchecked")
	private EasyExpression createEasyExpression(CustomExpression exp, DetachedCriteria dc,@SuppressWarnings("rawtypes") Set set,List<String> aliasList) {
		String propName = exp.getPropName();
		Object propValue = fetchPropValue(exp.getPropValue(), exp.getPropType());
		
		if(propName.equals("createdBy.orgnization.orgNo")){
			if(!aliasList.contains("createdBy")){
				dc.createAlias("createdBy", "createdBy");
				aliasList.add("createdBy");
			}
		
			dc.createAlias("createdBy.orgnization", "cbOrg");
			//aliasList.add("createdBy.orgnization");
			propName="cbOrg.orgNo";
		}
		else if (propName.indexOf(".")>-1 ) {
			String str = propName;
			if(set.contains(propName)==false){
				int idx = -1;
				while ((idx= str.indexOf("."))>-1 ) {
					String alias = str.substring(0, idx);
					if(!aliasList.contains(alias)){
						if("serviceLists.eventId".equals(propName)){
							dc.createAlias(alias, alias);
						}else{
							dc.createAlias(alias, alias,DetachedCriteria.LEFT_JOIN);
						}
						aliasList.add(alias);
					}
					str = str.substring(idx+1);
				}
				set.add(propName);
			}
		}
		EasyExpression easyExp =new EasyExpression(propName, propValue, " "+exp.getOperator()+" ");
		return easyExp;
	}
    
	/**
     * 根据过滤器条件创建表达式
     */
	@SuppressWarnings({ "unchecked", "unused" })
	private EasyExpression createEasyExpression(CustomExpression exp, DetachedCriteria dc,@SuppressWarnings("rawtypes") Set set) {
		String propName = exp.getPropName();
		Object propValue = fetchPropValue(exp.getPropValue(), exp.getPropType());
		
		if(propName.equals("createdBy.orgnization.orgNo")){
			dc.createAlias("createdBy", "cBy");
			dc.createAlias("cBy.orgnization", "cbOrg");
			propName="cbOrg.orgNo";
		}
		else if (propName.indexOf(".")>-1) {
			String str = propName;
			if(set.contains(propName)==false){
				int idx = -1;
				while ((idx= str.indexOf("."))>-1 ) {
					String alias = str.substring(0, idx);
					dc.createAlias(alias, alias,DetachedCriteria.LEFT_JOIN);
					str = str.substring(idx+1);
				}
				set.add(propName);
			}
		}
		EasyExpression easyExp =new EasyExpression(propName, propValue, " "+exp.getOperator()+" ");
		return easyExp;
	}

	
	/**
     * 转换变量类型
     */
	private Object fetchPropValue(String propValue, String propType){
		Object Object=null;
		if(propType.equals("Long")){
			Object=Long.valueOf(propValue);
		}else if(propType.equals("Int")){
			Object=Integer.valueOf(propValue);
		}else if(propType.equals("Double")){
			Object=Double.valueOf(propValue);
		}else if(propType.equals("String")){
			Object=propValue;
		}else if(propType.equals("Data")){
			Object = TimeUtils.parse(propValue,TimeUtils.DATETIME_PATTERN);
		}else if(propType.equals("Boolean")){
			Object=Boolean.valueOf(propValue);
		}
		return Object;
	}
	
	
	/**
     * 通过类名获取表的字段属性
     * @param className
     * @return Map
     * 
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map getClassMetaDataByClassName(String className){
		Map map=new HashMap();
		ClassMetadata meteData=super.getSessionFactory().getClassMetadata(className);
		String[] propertyNames=meteData.getPropertyNames();
		for(int i=0;i<propertyNames.length;i++){
			map.put(propertyNames[i], meteData.getPropertyType(propertyNames[i]).getName());
		}
		
		return map;
	}
	
	private CustomExpression findboolean(String rowGroup,String row){
	   CustomExpression ce1 = new CustomExpression();
	   ce1.setPropName(rowGroup);
	   ce1.setOperator("=");
	   ce1.setJoinType("and");
	   ce1.setPropType("Boolean");
	   if(row.equals("是")||row.equals("1")){
		   ce1.setPropValue("true");
	   }else{
		   ce1.setPropValue("false");
	   }
	   return ce1;
	}
	private CustomExpression findString(String rowGroup,String row){
		CustomExpression ce = new CustomExpression();
		   ce.setPropName(rowGroup);
		   ce.setOperator("=");
		   ce.setJoinType("and");
		   ce.setPropType("String");
		   ce.setPropValue(row);
		   return ce;
	}
	private CustomExpression findrowGrouporString(String rowGroup,String row){
		CustomExpression ce = new CustomExpression();
		   ce.setPropName(rowGroup);
		   ce.setOperator("=");
		   ce.setJoinType("or");
		   ce.setPropType("String");
		   ce.setPropValue(row);
		   return ce;
	}
	private CustomExpression findnotString(String rowGroup,String row){
		CustomExpression ce = new CustomExpression();
		   ce.setPropName(rowGroup);
		   ce.setOperator("!=");
		   ce.setJoinType("and");
		   ce.setPropType("String");
		   ce.setPropValue(row);
		   return ce;
	}
	private CustomExpression findLong(String columnGroup,String col){
		CustomExpression ce = new CustomExpression();
	   ce.setPropName(columnGroup);
	   ce.setOperator("=");
	   ce.setJoinType("and");
	   ce.setPropType("Long");
	   ce.setPropValue(col);
	   return ce;
	}
	private CustomExpression findnotLong(String rowGroup,String row){
		CustomExpression ce = new CustomExpression();
		   ce.setPropName(rowGroup);
		   ce.setOperator("!=");
		   ce.setJoinType("and");
		   ce.setPropType("Long");
		   ce.setPropValue(row);
		   return ce;
	}
    /**
     * 通过过滤器查询实体数据
     * @param filter
     * @return PageDTO
     * 
     */
    @SuppressWarnings("rawtypes")
	public PageDTO findPageByCustomFilter(CustomFilter filter,Long [] companyNos,int start,int limit,String sidx,String sord,KeyTransferDTO ktd) {
    	PageDTO pageDTO = null;
		if(filter!=null){
			List<String> aliaList=new ArrayList<String>(); 
			DetachedCriteria dc = DetachedCriteria.forEntityName(filter.getEntityClass());
			   Disjunction dj = Restrictions.disjunction();
			   Conjunction cj = Restrictions.conjunction();
			   Conjunction cj_end = Restrictions.conjunction();
			   dc.add(cj);
			   cj.add(dj);
			   dc.add(cj_end);
			   Set set=new HashSet();
			   List<CustomExpression> exps = filter.getExpressions();
			   List<CustomExpression> exps1 = new ArrayList<CustomExpression>();
			   String rowGroupsub="";
			   String columnGroupsu="";
			   if(ktd.getRowKey().lastIndexOf(".")!=-1){
				   rowGroupsub=ktd.getRowKey().substring(0,ktd.getRowKey().lastIndexOf("."));
			   }else{
				   rowGroupsub=ktd.getRowKey();
			   }
			   if(ktd.getColKey().lastIndexOf(".")!=-1){
				   columnGroupsu=ktd.getColKey().substring(0,ktd.getColKey().lastIndexOf("."));
			   }else{
				   columnGroupsu=ktd.getColKey();
			   }
			   if(exps!=null&&exps.size()>0){
				   for(CustomExpression ce : exps){
					   CustomExpression enity = new CustomExpression(); 
					   enity.setPropName(ce.getPropName());
					   enity.setOperator(ce.getOperator());
					   enity.setJoinType(ce.getJoinType());
					   enity.setPropType(ce.getPropType());
					   enity.setPropValue(ce.getPropValue());
					   String PropName="";
					   if(ce.getPropName().lastIndexOf(".")!=-1){
						   PropName=ce.getPropName().substring(0,ce.getPropName().lastIndexOf("."));
					   }else{
						   PropName=ce.getPropName();
					   }
					   if(!PropName.equals(rowGroupsub)&&!PropName.equals(columnGroupsu)){
						   exps1.add(enity);
					   }
				   }
			   }
			   if(ktd.getRowValue().equals("mutil")){
				   int i=ktd.getRowKey().indexOf("eno");
				   int i1=ktd.getRowKey().indexOf("Id");
				   int i2=ktd.getRowKey().indexOf("id");
				   int i3= ktd.getRowKey().indexOf("knownError");
				   if(i!=-1||i1!=-1||i2!=-1||i3!=-1){
					   cj_end.add(createEasyExpression(findnotLong(ktd.getRowKey(),"0"), dc,set,aliaList));
				   }else{
					   cj_end.add(createEasyExpression(findboolean(ktd.getRowKey(),"1"), dc,set,aliaList));
				   }
			   }else{
				   if(ktd.getRowKey().equals("isFCR")){
					   cj_end.add(createEasyExpression(findboolean(ktd.getRowKey(),ktd.getRowValue()), dc,set,aliaList));
				   }else if(ktd.getRowKey().equals("companyNo")){
					   cj_end.add(createEasyExpression(findLong(ktd.getRowKey(),ktd.getRowValue()), dc,set,aliaList));
				   }else{
					   if(!ktd.getRowValue().equals("")&&!ktd.getColValue().equals("false")){
						   if(ktd.getRowValue().indexOf(",")!=-1){
							   String[] values = ktd.getRowValue().split(",");
								for(String v:values){
									exps1.add(findrowGrouporString(ktd.getRowKey(),v));
								}
						   }else{
							   cj_end.add(createEasyExpression(findString(ktd.getRowKey(),ktd.getRowValue()), dc,set,aliaList));
						   }
					   }else{
						   cj_end.add(createEasyExpression(findnotString(ktd.getRowKey(),"'0'"), dc,set,aliaList));
						   cj_end.add(createEasyExpression(findnotString(ktd.getRowKey(),"null"), dc,set,aliaList));
						   cj_end.add(createEasyExpression(findnotString(ktd.getRowKey(),"'null'"), dc,set,aliaList));
					   }
					   
				   }
			   }
			   if(ktd.getColKey().equals("isFCR")){
				   cj_end.add(createEasyExpression(findboolean(ktd.getColKey(),ktd.getColValue()), dc,set,aliaList));
			   }else if(ktd.getColKey().equals("companyNo")){
				   cj_end.add(createEasyExpression(findLong(ktd.getColKey(),ktd.getColValue()), dc,set,aliaList));
			   }else{
				   if(!ktd.getColKey().equals("")){
					   int en=ktd.getColKey().indexOf("eno");
					   if((en!=-1||ktd.getColKey().equals("companyNo"))){
						   cj_end.add(createEasyExpression(findLong(ktd.getColKey(),ktd.getColValue()), dc,set,aliaList));
					   }else if(!ktd.getColValue().equals("")){
						   cj_end.add(createEasyExpression(findString(ktd.getColKey(),ktd.getColValue()), dc,set,aliaList));
					   }else{
						   cj_end.add(createEasyExpression(findnotString(ktd.getColKey(),"'0'"), dc,set,aliaList));
						   cj_end.add(createEasyExpression(findnotString(ktd.getColKey(),"null"), dc,set,aliaList));
						   cj_end.add(createEasyExpression(findnotString(ktd.getColKey(),"'null'"), dc,set,aliaList));
					   }
				   }
			   }
			   
			   //只查找我负责的公司
			   if(companyNos!=null && companyNos.length>0 &&filter!=null&& "request".equals(filter.getFilterCategory())){
				   dc.add(Restrictions.in("companyNo", companyNos));
			   }
			   
			  //排序
	           dc = DaoUtils.orderBy(sidx, sord, dc);
			   
	           if(exps1!=null&&exps1.size()>0){
	        	   //上一个的连接类型
	        	   String joinType = "";
	        	   for (CustomExpression exp:exps1) {
	        		   //如果上一个连接类型是and
	        		   if("and".equals(joinType)){
	        			   dj = Restrictions.disjunction();
	        			   cj.add(dj);
	        		   }
	        		   dj.add(createEasyExpression(exp, dc,set,aliaList));
	        		   joinType = exp.getJoinType();
	        	   }
			   }
	           pageDTO = super.findPageByCriteria(dc, start, limit);
		}
        return pageDTO;
    }
}